// xc/components/cash/cashout.js

var behaviorsbasic = require('../../behaviors/basic')
var actbill = require('../../model/cashout')

Component({
  behaviors: [behaviorsbasic],
  options: {
    addGlobalClass: true,
    multipleSlots: true
  },
  /**
   * 组件的属性列表
   */
  properties: {
    themcolor: {
      type: Object,
      value: null,
    },
    xtitle: {
      type: String,
      default: "提现"
    },
    formdata: {
      type: Object,
      value: {
        phone: "",
        simg: "",
        account: "",
        name: "",
        moreinfo: "",
        amount: "",
        paymentmode: "",
      },
    }
  },

  /**
   * 组件的初始数据
   */
  data: {
    isshow: false,
    navcur: "wechat",
    cashwith: {},
    payments: {},
    navlist: [{
        val: "wechat",
        label: "微信提现"
      },
      {val:"alipay",label:"支付宝提现"},
      // {val:"bank",label:"银行卡提现"},
      {val:"balance",label:"余额"},
    ],
    navlistkey: {
      'wechat': '微信提现',
      'alipay': '支付宝提现',
      'bank': '银行卡提现',
      'balance': '余额提现',
    },
    label: {
      wechat: {
        account: "微信帐号",
        name: "微信实名"
      },
      alipay: {
        account: "支付宝帐号",
        name: "支付宝实名"
      },
      bank: {
        account: "银行卡号",
        name: "开户人姓名",
        moreinfo: "银行名称"
      },
      balance: {
        account: "帐号",
        name: "姓名"
      },
    },
    helpeer: {
      isshow: false,
      imgurl: ""
    },
    fileList: [],
    brokerage: 0,
    errormessage: "",
    mode: "", //club 团长
    
  },
  ready() {
    var that = this;


  },

  /**
   * 组件的方法列表
   */
  methods: {
    // 全部提现
    allbrokerage(e) {
      var maxbrokerage = (this.data.brokerage * 0.01).toFixed(2)
      this.setData({
        'formdata.amount': maxbrokerage
      })

    },
    // 判断输入金额 
    amountinput(e) {
      var amount = e.detail.value.replace(/[^\d.]/g, '');

      var ilen = amount.length
      var errormessage = ""
      var updatemodel = {}
      if ((ilen > 2 && (amount.indexOf(".0") == (ilen - 2))) || (amount.indexOf(".") == 1 && ilen == 2) || amount == "0") {
        this.setData({
          'formdata.amount': amount
        })
        return
      } else {
        var stramount = amount
        if (ilen > 1) {
          stramount = stramount.replace(/\b(0+)/gi, "")
          if (stramount.indexOf(".") == 0 || stramount == "") {
            stramount = "0" + stramount
          }
          stramount = stramount.replace(/^(\-)*(\d+)\.(\d\d).*$/, '$1$2.$3')
        }
        var navcur = this.data.navcur
        amount = parseInt(amount * 100)
        var payment = this.data.payments[navcur]
        if (amount < (payment.startmoney * 100)) {
          errormessage = "提现金额不能为小于" + payment.startmoney
        } else if (amount > parseInt(this.data.brokerage)) {
          var maxbrokerage = (this.data.brokerage * 0.01).toFixed(2)
          updatemodel['formdata.amount'] = maxbrokerage;
        } else {
          updatemodel['formdata.amount'] = stramount;
        }
      }
      updatemodel['errormessage'] = errormessage
      this.setData(updatemodel)
    },
    errormessage() {
      wx.showModal({
        title: '错误当前',
        content: '错误当前',
        confirmText: "关闭",
        showCancel: false,
        success(res) {
          if (res.confirm) {
            that.closefunc()
          }
        }
      })
    },
    showmodel(mode) {
      var that = this;
      var app = getApp()
      var updatemodel = {
        isshow: true
      }
      this.data.mode = mode
      switch (mode) {
        case "club": {
          updatemodel["xtitle"] = "团长提现"
          var cashwith = app.globalData.configdata.club.cashwith
          if (cashwith && cashwith["status"] == 1) {
            this.changenavlist(cashwith['paymentmode'])
            this.setData({
              payments: cashwith["payments"]
            })
            var actleadgroup = app.globalData.actleadgroup;
            if (!actleadgroup) {
              that.errormessage();
            } else {
              actbill.brokerage(actleadgroup.id, mode).then(function (result) {
                if (result["status"] == 1) {
                  that.setData({
                    brokerage: result["obj"]["brokerage"]
                  })
                }else{
                  wx.showToast({
                    icon:"none",
                    title: result['message'],
                  })
                }
              })
            }
          } else {
            that.errormessage();
            return;
          }
          break;
        }
        case "distr": {

          var cashwith = app.globalData.configdata.distribution.cashwith
      
          if (cashwith && cashwith["status"] == 1) {
            console.log("cashwith")
            console.log(cashwith)

            this.changenavlist(cashwith['paymentmode'])

            updatemodel["payments"] = cashwith["payments"]
            console.log("cashwith[payments")
            console.log(cashwith["payments"])

            var member_id = app.globalData.member.member_id
            actbill.brokerage(member_id, mode).then(function (result) {
              if (result["status"] == 1) {
                that.setData({
                  brokerage: result["obj"]["brokerage"]
                })
              }
            })
          } else {
            that.errormessage();
            return;
          }
          break;
        }
        case "money": {
          updatemodel["xtitle"] = "红包提现"


          if (app.globalData.configdata.money) {
            var cashwith = app.globalData.configdata.money.cashwith
           
            if (cashwith && cashwith["status"] == 1) {
              this.changenavlist(cashwith['paymentmode'])

              updatemodel["payments"] = cashwith["payments"]

              var member_id = app.globalData.member.member_id


              actbill.brokerage(member_id, mode).then(function (result) {
                if (result["status"] == 1) {
                  that.setData({
                    brokerage: result["obj"]
                  })
                }
              })
            } else {
              that.errormessage();
            }
          } else {
            that.errormessage();
          }
          break;
        }
        case "amount": {
          updatemodel["xtitle"] = "余额提现"

          console.log("app.globalData.configdata")
          console.log(app.globalData.configdata.payment)

          if (app.globalData.configdata.payment) {
            var cashwith = app.globalData.configdata.payment.cashwith
           
            if (cashwith && cashwith["status"] == 1) {
              this.changenavlist(cashwith['paymentmode'])

              updatemodel["payments"] = cashwith["payments"]

              var member_id = app.globalData.member.member_id


              actbill.brokerage(member_id, mode).then(function (result) {
                if (result["status"] == 1) {
                  that.setData({
                    brokerage: result["obj"]
                  })
                }
              })
            } else {
              that.errormessage();
            }
          } else {
            that.errormessage();
          }
          break;
        }

      }
      this.setData(updatemodel)
      return;



    },
    //修改navlist
    changenavlist(paymentmode) {
      var navlistkey = this.data.navlistkey;
      var list = [];
      for (var i in paymentmode) {
        if (navlistkey[paymentmode[i]]) {
          var item = {
            val: paymentmode[i],
            label: navlistkey[paymentmode[i]]
          };
          list.push(item)
        }
      }
      this.setData({
        navcur:paymentmode[0]?paymentmode[0]:'',
        navlist: list
      })
    },
    // 获取手机号
    getPhoneNumber(e) {
      var that = this;
      var dataset = e.currentTarget.dataset;
      var encryptedData = e.detail.encryptedData;
      // if (!encryptedData) {
      //   return;
      // }
      var iv = e.detail.iv;
      var code = e.detail.code;

      var app = getApp();
      app.toolv2.getphone(encryptedData, iv,code).then(function (data) {
        if (data["code"] == "success") {
          var upatemodel = {};
          upatemodel["formdata.phone"] = data["obj"].phoneNumber;
          that.setData(upatemodel)
        }
      });
    },

    closefunc: function (e) {
      this.setData({
        isshow: false
      })
    },
    Changenav: function (e) {

      this.setData({
        navcur: e.detail.name
      })

    },
    //二维码帮助
    showerhelper: function () {
      var app = getApp()
      var basicelink = app.globalData.configdata.eg.basicelink;
      var imgurl = basicelink + "tixian/" + this.data.navcur + "_teach.jpg"
      var helpeer = {
        imgurl,
        isshow: true
      }
      this.setData({
        helpeer
      })


    },
    //验证表单
    checkForm: function (field) {
      var that = this
      var allfield = ["account", "name", "phone", "simg"]
      var formdata = that.data.formdata
      var navcur = this.data.navcur
      if (field) {
        var updatefield = {};
        var bvalue = false
        if (formdata[field]) {
          updatefield["vildfield." + field] = true
          bvalue = true
        } else {
          updatefield["vildfield." + field] = false
        }
        that.setData(updatefield)
        return bvalue
      } else {
        var valid = true;
        var vildfield = {};
        var fieldvals = this.data.payments[navcur].field
        var fieldval = 1
        allfield.forEach((item, index) => {
          if ((fieldvals & fieldval) != fieldval || that.data.formdata[item]) {
            vildfield[item] = true
          } else {
            vildfield[item] = false
            valid = false
          }
          fieldval *= 2
        })
        that.setData({
          vildfield
        })
        return valid;
      }
    },
    savefilefunc(file) {
      var app = getApp()
      var that = this
      app.toolv2.uploadFile(file.path).then(function (item) {
        var fileList = [{
          ...file,
          url: item.obj.fullpath
        }]
        that.data.formdata.simg = item.obj.fullpath;
        that.setData({
          fileList
        });
      })
    },
    afterRead(event) {
      var that = this
      const {
        file
      } = event.detail
      if (file.constructor == Array) {
        file.forEach(item => {
          that.savefilefunc(item)
        })
      } else {
        that.savefilefunc(file)
      }
    },
    popupclose: function (e) {
      var dataset = e.currentTarget.dataset
      var updatemodel = {}
      updatemodel[dataset.field] = false
      this.setData(updatemodel)
    },
    watchInput: function (e) {
      var dataset = e.target.dataset
      this.data.formdata[dataset.field] = e.detail
      this.checkForm(dataset.field)
    },
    Submit: function (e) {
      if(this.data.submiting){
        return false
      }

      var that = this
      var navcur = this.data.navcur
      var amount = parseInt(this.data.formdata.amount * 100)
      var brokerage = parseInt(this.data.brokerage)
      var startmoney = parseInt(this.data.payments[navcur].startmoney) * 100
      if (amount > brokerage) {
        wx.showModal({
          title: '提现金额不能大于可提现金额',
          content: '提现金额不能大于可提现金额',
          showCancel: false
        })
        return false
      } else if (amount == 0) {
        wx.showModal({
          title: '提现金额不能为零',
          content: '提现金额不能为零',
          showCancel: false
        })
        return
      } else if (amount < startmoney) {
        wx.showModal({
          title: '提现金额不能小于' + (startmoney / 100) + "元",
          content: '提现金额不能小于' + (startmoney / 100) + "元",
          showCancel: false
        })
        return
      }
      var reslut = this.checkForm()


      if (reslut) {
        that.setData({submiting:true})
        that.data.formdata['paymentmode'] = this.data.navcur

       

        actbill.withdrawal(that.data.formdata, that.data.mode).then(function (res) {


          if (res["status"] == "1") {
            var str = {};
            str['obj'] = res["obj"];
            str['member'] = res["member"];
            that.triggerEvent('aftercashout', str)
            if (res["member"]) {
              var app = getApp()
              app.globalData.member = res["member"];
            }
            wx.showModal({
              title: "操作成功",
              content: "操作成功",
              confirmText: "查看记录",
              cancelText: "关闭",
              success(res) {
                if (res.confirm) {
                  that.triggerEvent('cashoutrecord', res["obj"])
                } else if (res.cancel) {
                  console.log('用户点击取消')
                }
                that.setData({
                  isshow: false
                })
              }
            })
          } else {
            wx.showModal({
              title: res["message"],
              content: res["message"],
              showCancel: false
            })

          }
          that.setData({submiting:false})

        })
      }
    }
  }
})